package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.flyco.roundview.RoundTextView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.app.utils.ViewExtensionKt;
import com.kmproject.haifu.di.component.DaggerFansListComponent;
import com.kmproject.haifu.mvp.contract.FansListContract;
import com.kmproject.haifu.mvp.model.entity.beans.UserAttentionBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsAttentionAdd;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsAttentionCancel;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsGetFansList;
import com.kmproject.haifu.mvp.presenter.FansListPresenter;
import com.kmproject.haifu.mvp.ui.adapter.BaseRecyclerAdapter;
import com.kmproject.haifu.mvp.ui.holder.SmartViewHolder;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.OnRefreshLoadMoreListener2;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;
import static com.luliang.shapeutils.DevShapeUtils.getContext;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 08/20/2019 19:22
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class FansListActivity extends BaseActivity<FansListPresenter> implements FansListContract.View {
    @BindView(R.id.toolbar_title)
    TextView toolbar_title;
    @BindView(R.id.srl_follow_list)
    PullToRefreshView srl_follow_list;
    @BindView(R.id.rv_follow_list)
    RecyclerView rv_follow_list;
    @BindView(R.id.i_empty)
    View empty;
    /**
     * 0-用户；1-店铺
     */
    private int type;
    private String userId;
    private boolean isCurrentUserOrStore;//是否当前用户或当前用户的店铺

    private ReqParamsGetFansList reqParams;

    private BaseRecyclerAdapter<UserAttentionBean> adapter;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerFansListComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_fans_list; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        reqParams = new ReqParamsGetFansList();
        UserBean userBean = DataHelper.getDeviceData(this, AppConstant.USER_INFO);//获取用户信息
        Intent intent = getIntent();
        if (intent != null) {
            userId = intent.getStringExtra("userId");
            type = intent.getIntExtra("type", 0);
        }
        if (userBean != null && userBean.getUserId() != null) {
            if (userId.equals(userBean.getUserId())) {
                isCurrentUserOrStore = true;
                toolbar_title.setText(getString(R.string.fans_title_my));
                reqParams.setType(0);
                reqParams.setUserId(userId);
            } else {
                if (type == 1) {
                    toolbar_title.setText(getString(R.string.fans_title_store));
                    reqParams.setType(1);
                    reqParams.setStoreId(userId);
                } else {
                    toolbar_title.setText(getString(R.string.fans_title_ta));
                    reqParams.setType(2);
                    reqParams.setUserId(userId);
                }
            }
        }

        rv_follow_list.addItemDecoration(new CustomGridItemDecoration.Builder(this).setVerticalSpan(0f).
                setHorizontalSpan(1f).setColor(ContextCompat.getColor(this, R.color.common_menu_text)).setShowLastLine(false).build());
        ArmsUtils.configRecyclerView(rv_follow_list, new LinearLayoutManager(this));
        rv_follow_list.setItemAnimator(new DefaultItemAnimator());
        srl_follow_list.setEnableRefresh(true);
        srl_follow_list.setEnableAutoLoadMore(false);
        srl_follow_list.setEnableHeaderTranslationContent(true);

        adapter = new BaseRecyclerAdapter<UserAttentionBean>(R.layout.item_follow_user) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, UserAttentionBean model, int position) {
                holder.image(R.id.imv_user_head_portrait, model.getAvatar());
                holder.image(R.id.imv_level_icon, model.getMemberLevelHeadImage());
                holder.text(R.id.tv_user_name, model.getNickName());
                StringBuilder sb = new StringBuilder();
                // 拼接注册时间/性别/状态
                sb.append(model.getRegisterLongTime());
                sb.append(model.getUserSex());
                sb.append(model.getOnlineStatus());
                holder.text(R.id.tv_user_base_info, sb);
                RoundTextView rtv_operation = (RoundTextView) holder.findViewById(R.id.rtv_operation);
                if (model.getIsAttention() == 1) {// 已关注
                    rtv_operation.getDelegate().setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.color_AAAAAA));
                    rtv_operation.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
                    rtv_operation.setText(getString(R.string.is_followed));
                } else {
                    rtv_operation.getDelegate().setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.color_F9D35A));
                    rtv_operation.setTextColor(ContextCompat.getColor(getContext(), R.color.common_title_text));
                    rtv_operation.setText(getString(R.string.follow_add));
                }

                rtv_operation.setTag(position);
                rtv_operation.setOnClickListener(v -> {
                    int pos = (int) v.getTag();
                    UserAttentionBean uab = (UserAttentionBean) adapter.getItem(pos);
                    assert mPresenter != null;
                    if (uab.getIsAttention() == 1) {
                        //关注的类型:0-用户,1-店铺
                        ReqParamsAttentionCancel reqParamsAttentionCancel = new ReqParamsAttentionCancel();
                        reqParamsAttentionCancel.setType(0);//粉丝只可能是人
                        reqParamsAttentionCancel.setIds(Collections.singletonList(uab.getUserId()));
                        mPresenter.unFollow(reqParamsAttentionCancel);
                    } else {
                        ReqParamsAttentionAdd reqParamsAttentionAdd = new ReqParamsAttentionAdd();
                        reqParamsAttentionAdd.setType(0);
                        reqParamsAttentionAdd.setId(uab.getUserId());
                        mPresenter.follow(reqParamsAttentionAdd);
                    }
                });
            }
        };
        rv_follow_list.setAdapter(adapter);

        adapter.setOnItemClickListener((parent, view, position, id) -> {
//            ArmsUtils.makeText(getContext(), "index:" + adapter.getRealItemPosition(position));
        });

        srl_follow_list.setOnRefreshLoadMoreListener2(new OnRefreshLoadMoreListener2() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                // 加载更多
                reqParams.setPage(curPageNo);
                getListData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                // 刷新
                reqParams.setPage(curPageNo);
                getListData();
            }
        });
        getListData();
    }

    private void getListData() {
        assert mPresenter != null;
        if (isCurrentUserOrStore) {
            mPresenter.getFansList4CurrentUserOrStore(reqParams);
        } else {
            mPresenter.getFansList4OtherUserOrStore(reqParams);
        }
    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void followSuccess() {
        showMessage(getString(R.string.success));
        reqParams.setPage(1);
        getListData();
    }

    @Override
    public void unFollowSuccess() {
        showMessage(getString(R.string.success));
        reqParams.setPage(1);
        getListData();
    }

    @Override
    public void getFansList4UserIdSuccess(List<UserAttentionBean> list) {
        srl_follow_list.finishLoadMore();
        srl_follow_list.finishRefresh();
        if (list != null && !list.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rv_follow_list, true);
            if (ViewExtensionKt.isPullDown(srl_follow_list, list.size(), reqParams.getLimit())) {
                adapter.refresh(list);
            } else {
                adapter.loadMore(list);
            }
        } else {
            if (reqParams.getPage() > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rv_follow_list, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rv_follow_list, false);
            }
        }
    }

    @Override
    public void getListFailed() {
        srl_follow_list.finishLoadMore();
        srl_follow_list.finishRefresh();
        if (reqParams.getPage() > 1) {
            reqParams.setPage(reqParams.getPage() - 1);
        }
    }
}
